{include file="base/_meta" /}
<style>
    .layui-steps-simple .layui-tab-title li {
        color: #fff;
    }
</style>
</head>
<body>

<!-- 正文开始 -->
<div class="layui-fluid layui-form">
    <div class="layui-card">
        <div class="layui-card-body">

            <input type="hidden" name="id" value="{$data.id|default=''}">

            <div class="layui-tab layui-steps layui-steps-simple">
                <ul class="layui-tab-title">
                    <li class="layui-this">基础信息</li>
                    <li>规格信息</li>
                    <li>商品详情</li>
                    <li>其他设置</li>
                </ul>
                <div class="layui-tab-content">
                    <div class="layui-tab-item layui-show">

                        <div class="layui-form-item">
                            <label class="layui-form-label">商品分类:</label>
                            <div class="layui-input-block">
                                <div id="cate" class="xm-select-cate"></div>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label layui-form-required">商品名称:</label>
                            <div class="layui-input-block">
                                <input name="name" placeholder="请输入名称" class="layui-input"
                                       lay-verType="tips" lay-verify="required" required autocomplete="off"
                                       value="{$data.name|default=''}"/>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">关键字:</label>
                            <div class="layui-input-block">
                                <input name="keywords" placeholder="请输入商品关键字" class="layui-input"
                                       lay-verType="tips" autocomplete="off" value="{$data.keywords|default=''}"/>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">商品简介:</label>
                            <div class="layui-input-block">
                                <textarea name="desc" placeholder="请输入商品简介" class="layui-textarea">{$data.desc|default=''}</textarea>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">缩略图：</label>
                            <div class="layui-input-block">
                                <div class="layui-upload-drag" id="img_thumb" onclick="upload_file('img_thumb',1)">
                                    <div>
                                        <img src="{$data.img_thumb|default='/static/images/default_img.png'}"
                                             alt="上传成功后渲染" style="max-width: 96px">
                                        <input type="hidden" name="img_thumb" value="{$data.img_thumb|default='/static/images/default_img.png'}">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">轮播图：</label>
                            <div class="layui-input-block carouselDiv">
                                <!--多文件上传-->
                                <button type="button" class="layui-btn layui-btn-normal" id="uploads_file"
                                        onclick="upload_file('uploads_file',2)">选择多文件
                                </button>
                                <div class="layui-upload-list">
                                    <!--上传文件列表-->
                                    <div class="img-div layui-clear">
                                        {notempty name="$data.carousel"}
                                        <?php $carousel = explode(',',$data['carousel']);?>
                                        {volist name="$carousel" id="voCarousel"}
                                        <div class="pull-left upload-img-div">
                                            <img src="{$voCarousel}" width="100%">
                                            <i class="layui-icon layui-icon-close-fill upload-file-del" data-index="{$key}"></i>
                                        </div>
                                        {/volist}
                                        {/notempty}
                                    </div>
                                    <!--隐藏域，放文件路径使用-->
                                    <input type="hidden" name="carousel" value="{$data.carousel|default=''}">
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">状态:</label>
                            <div class="layui-input-block">
                                <input type="radio" name="put_on" value="10" title="上架" {neq name="$data.put_on"
                                       value="20" }checked{/neq}>
                                <input type="radio" name="put_on" value="20" title="下架" {eq name="$data.put_on"
                                       value="20" }checked{/eq}>
                            </div>
                        </div>

                    </div>
                    <div class="layui-tab-item">
                        <!--                        选择规格-->
                        <div class="layui-form-item">
                            <label class="layui-form-label">规格名:</label>
                            <div class="layui-input-inline">
                                <select lay-filter="format_name" id="format_name">
                                    <option value=""></option>
                                    {notempty name="formatName"}
                                    {volist name="formatName" id="voFormatName"}
                                    <option value="{$voFormatName.id}">{$voFormatName.name}</option>
                                    {/volist}
                                    {/notempty}
                                </select>
                            </div>
                            <button class="layui-btn" id="addFormatName">添加</button>
                        </div>
                        <!--                        规格详情-->
                        <div id="format-div"></div>
                        <!--                        生成规格-->
                        <div class="layui-form-item">
                            <label class="layui-form-label"></label>
                            <div class="layui-input-block">
                                <div class="layui-btn-group">
                                    <button type="button" class="layui-btn" id="generate_format">生成</button>
                                </div>
                            </div>
                        </div>
                        <!--                        规格表格-->
                        <?php $display = empty($data['format'])?'none':'block'; ?>
                        <div class="layui-form-item" id="format_table_temp_div" style="display: {$display};">
                            <label class="layui-form-label">批量设置</label>
                            <div class="layui-input-block">
                                <table class="layui-table" id="format_table_temp">
                                    <thead>
                                    <tr>
                                        <td>图片</td>
                                        <td>售价</td>
                                        <td>成本价</td>
                                        <td>原价</td>
                                        <td>库存</td>
                                        <td>重量(KG)</td>
                                        <td>体积(m³)</td>
                                        <td>操作</td>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <tr>
                                        <td>
                                            <div class="layui-upload-drag" id="img_temp" onclick="upload_file('img_temp',1)">
                                                <div>
                                                    <img src="/static/images/default_img.png" style="max-width: 46px">
                                                    <input type="hidden" name="format_temp[img]" value="">
                                                </div>
                                            </div>
                                        </td>
                                        <td><input type="number" name="format_temp[price]" class="layui-input" autocomplete="off"
                                                   value="0"/></td>
                                        <td><input type="number" name="format_temp[cost_price]" class="layui-input"
                                                   autocomplete="off" value="0"/></td>
                                        <td><input type="number" name="format_temp[original_price]" class="layui-input"
                                                   autocomplete="off" value="0"/></td>
                                        <td><input type="number" name="format_temp[stock]" class="layui-input" autocomplete="off"
                                                   value="0"/></td>
                                        <td><input type="number" name="format_temp[weight]" class="layui-input" autocomplete="off"
                                                   value="0"/></td>
                                        <td><input type="number" name="format_temp[volume]" class="layui-input" autocomplete="off"
                                                   value="0"/></td>
                                        <td>
                                            <button class="layui-btn layui-btn-xs" lay-filter="setUpFormat" lay-submit>批量设置</button>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="layui-form-item" id="format_table_div" style="display: {$display};">
                            <label class="layui-form-label">商品属性</label>
                            <div class="layui-input-block">
                                <table class="layui-table" id="format_table">
                                    {notempty name="$data.format"}
                                    <thead>
                                    <tr>
                                        <?php $skuThead = explode(',',$data['format'][0]['sku']);?>
                                        {for start="0" end="count($skuThead)"}
                                        <td>{:getGoodsFormatNameById(explode(':',$skuThead[$i])[0])}</td>
                                        {/for}
                                        <td>图片</td>
                                        <td>售价</td>
                                        <td>成本价</td>
                                        <td>原价</td>
                                        <td>库存</td>
                                        <td>重量(KG)</td>
                                        <td>体积(m³)</td>
                                        <td>操作</td>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {volist name="$data.format" id="voFormat"}
                                    <tr>
                                        <input type="hidden" name="format[id][]" value="{$voFormat.id}">
                                        <input type="hidden" name="format[sku][]" value="{$data['format'][$key]['sku']}">
                                        <?php $skuTbody = explode(',',$data['format'][$key]['sku']);?>
                                        {for start="0" end="count($skuThead)"}
                                        <td>{:getGoodsFormatValueById(explode(':',$skuTbody[$i])[1])}</td>
                                        {/for}
                                        <td>
                                            <div class="layui-upload-drag" id="img{$voFormat.id}{$key}" onclick="upload_file('img{$voFormat.id}{$key}',1)">
                                                <div>
                                                    <img src="{$voFormat.img|default='/static/images/default_img.png'}" style="max-width: 46px">
                                                    <input type="hidden" name="format[img][]" value="">
                                                </div>
                                            </div>
                                        </td>
                                        <td><input type="number" name="format[price][]" class="layui-input" autocomplete="off"
                                                   value="{$voFormat.price}"/></td>
                                        <td><input type="number" name="format[cost_price][]" class="layui-input"
                                                   autocomplete="off" value="{$voFormat.cost_price}"/></td>
                                        <td><input type="number" name="format[original_price][]" class="layui-input"
                                                   autocomplete="off" value="{$voFormat.original_price}"/></td>
                                        <td><input type="number" name="format[stock][]" class="layui-input" autocomplete="off"
                                                   value="{$voFormat.stock}"/></td>
                                        <td><input type="number" name="format[weight][]" class="layui-input" autocomplete="off"
                                                   value="{$voFormat.weight}"/></td>
                                        <td><input type="number" name="format[volume][]" class="layui-input" autocomplete="off"
                                                   value="{$voFormat.volume}"/></td>
                                        <td>
                                            <button class="layui-btn layui-btn-xs layui-btn-danger format-del">删除</button>
                                        </td>
                                    </tr>
                                    {/volist}
                                    </tbody>
                                    {/notempty}
                                </table>
                            </div>
                        </div>

                    </div>
                    <div class="layui-tab-item">

                        <div class="layui-form-item layui-form-text">
                            <script id="container" name="content" type="text/plain">
                                {:html_entity_decode($data.content)}
                            </script>
                        </div>

                    </div>
                    <div class="layui-tab-item">

                        <div class="layui-row">
                            <div class="layui-col-md4 layui-col-sm12">

                                <div class="layui-form-item">
                                    <label class="layui-form-label">排序:</label>
                                    <div class="layui-input-block">
                                        <input name="sort" placeholder="请输入名称" class="layui-input" required
                                               autocomplete="off" type="number" value="{$data.sort|default='0'}"/>
                                    </div>
                                </div>

                                <div class="layui-form-item">
                                    <label class="layui-form-label">置顶:</label>
                                    <div class="layui-input-block">
                                        <input type="radio" name="top" value="10" title="置顶" {neq name="$data.top"
                                               value="20" }checked{/neq}>
                                        <input type="radio" name="top" value="20" title="不置顶" {eq name="$data.top"
                                               value="20" }checked{/eq}>
                                    </div>
                                </div>

                            </div>
                            <div class="layui-col-md4 layui-col-sm12"></div>
                            <div class="layui-col-md4 layui-col-sm12"></div>
                        </div>

                    </div>
                </div>
            </div>

            <div class="layui-row">

                <div class="layui-form-item">
                    <button class="layui-btn" lay-filter="authoritiesEditSubmit" lay-submit>保存</button>
                </div>

            </div>
        </div>
    </div>
</div>

<!-- js部分 -->
{include file="base/_script" /}
<!-- 配置文件 -->
<script type="text/javascript" src="__LIB__/ueditor/ueditor.config.js"></script>
<!-- 编辑器源码文件 -->
<script type="text/javascript" src="__LIB__/ueditor/ueditor.all.js"></script>
<script>
    layui.use(['layer', 'form', 'admin', 'xmSelect', 'element'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var admin = layui.admin;
        var xmSelect = layui.xmSelect;
        var element = layui.element;
        var index = 0;
        var format = [];

        var ue = UE.getEditor('container', {
            initialFrameHeight: 500,
            wordCount: false,
        });

        // tab切换事件
        element.on('tab(info)', function (data) {
            if (data.index > index) {
                element.tabChange('info', 'index' + index);
            }
        });

        // 获取分类
        $.post("{:url('goods/goods_cate_tree')}", function (ret) {
            var cateXmSelect = xmSelect.render({
                el: '#cate',
                height: '250px',
                name: "goods_cate_id",
                data: ret.data,
                initValue: {$data.cate_id |default = "[]"},
                model: {
                    label: {type: 'text'},
                },
                prop: {
                    name: 'name',
                    value: 'id'
                },
                tree: {
                    show: true,
                    indent: 15,
                    strict: true,
                    expandedKeys: true
                }
            })
        })

        /* 监听表单提交 */
        form.on('submit(authoritiesEditSubmit)', function (data) {
            data.field.content = ue.getContent();
            $.post("{:url('goods/goods_save')}", data.field, function (res) {
                if (res.code == 0) {
                    layer.msg(res.msg, {icon: 1, time: 1000}, function () {
                        admin.closeThisTabs()
                    });
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }, 'json');
            return false;
        });
        form.on('submit(setUpFormat)', function (data) {
            let temp = data.field
            $("input[name^='format[img]']").prev('img').attr('src',temp['format_temp[img]'])
            $("input[name^='format[img]']").val(temp['format_temp[img]'])
            $("input[name^='format[cost_price]']").val(temp['format_temp[cost_price]'])
            $("input[name^='format[original_price]']").val(temp['format_temp[original_price]'])
            $("input[name^='format[price]']").val(temp['format_temp[price]'])
            $("input[name^='format[stock]']").val(temp['format_temp[stock]'])
            $("input[name^='format[volume]']").val(temp['format_temp[volume]'])
            $("input[name^='format[weight]']").val(temp['format_temp[weight]'])
            return false;
        });

        /* 监听规格名选择 */
        $("#addFormatName").click(function () {
            let value = $("#format_name").val()
            let text = $("#format_name").find("option:selected").text();
            $.post("{:url('goods/getFormatValue')}", {goods_format_name_id: value}, function (ret) {
                let html = '<fieldset class="layui-elem-field">\n' +
                    '  <legend data-formatnameid="' + value + '" data-formatnametext="' + text + '">' + text + '<i class="layui-icon layui-icon-close-fill format-name-del"></i></legend>\n' +
                    '  <div class="layui-field-box">\n';
                $.each(ret.data, function (v, o) {
                    html += '<button class="layui-btn layui-btn-sm layui-btn-primary" data-formatvalueid="' + o.id + '" data-formatvaluetext="' + o.name + '" data-pid="' + value + '">' + o.name + '<i class="layui-icon layui-icon-close-fill format-value-del"></i></button>';
                })
                html += '  </div>\n' +
                    '</fieldset>';
                $("#format-div").append(html)
                // 删除值
                $(".format-value-del").click(function () {
                    $(this).parent().remove()
                })
                // 删除规格名
                $(".format-name-del").click(function () {
                    $(this).parent().parent().remove()
                })
            })
        })

        /* 生成规格 */
        $("#generate_format").click(function () {
            let html = '<thead><tr>';
            let valueArr = [];
            // 生成表头
            $("#format-div").find('fieldset').each(function (index) {
                let name_text = $(this).find('legend').data('formatnametext')
                html += '<td>' + name_text + '</td>';
            })
            html += '<td>图片</td>' +
                '<td>售价</td>' +
                '<td>成本价</td>' +
                '<td>原价</td>' +
                '<td>库存</td>' +
                '<td>重量(KG)</td>' +
                '<td>体积(m³)</td>' +
                '<td>操作</td>' +
                '</tr></thead>';

            // 生成表格
            html += '<tbody>';
            $("#format-div").find('fieldset').each(function (index) {
                let name_id = $(this).find('legend').data('formatnameid')
                valueArr[index] = []

                $("#format-div").find('.layui-field-box').find('button').each(function (index2) {
                    let value_id = $(this).data('formatvalueid')
                    let value_text = $(this).data('formatvaluetext')
                    let pid = $(this).data('pid')
                    if (pid == name_id) {
                        valueArr[index][index2] = {text: value_text, pid: pid, id: value_id}
                    }
                })
            })
            // 得到需要的数组
            let tbodyArr = calcDescartes(valueArr);
            console.log(tbodyArr)
            tbodyArr.forEach(function (i, index) {
                html += '<tr>';

                if (typeof i.id == 'number'){
                    // 如果是单规格
                    html += '<td>' + i.text + '<input type="hidden" name="format[sku][' + index + '][]" value="' + i.pid + ':' + i.id + '"></td>';
                }else{
                    // 多规格
                    i.forEach(function (j) {
                        html += '<td>' + j.text + '<input type="hidden" name="format[sku][' + index + '][]" value="' + j.pid + ':' + j.id + '"></td>';
                    })
                }

                html += '<td><div class="layui-upload-drag" id="img' + index + '" onclick="upload_file(\'img' + index + '\',1)">\n' +
                    '    <div>\n' +
                    '        <img src="/static/images/default_img.png" style="max-width: 46px">\n' +
                    '        <input type="hidden" name="format[img][]" value="">\n' +
                    '    </div>\n' +
                    '</div></td>';
                html += '<td><input type="number" name="format[price][]" class="layui-input" autocomplete="off" value=""/></td>';
                html += '<td><input type="number" name="format[cost_price][]" class="layui-input" autocomplete="off" value=""/></td>';
                html += '<td><input type="number" name="format[original_price][]" class="layui-input" autocomplete="off" value=""/></td>';
                html += '<td><input type="number" name="format[stock][]" class="layui-input" autocomplete="off" value=""/></td>';
                html += '<td><input type="number" name="format[weight][]" class="layui-input" autocomplete="off" value=""/></td>';
                html += '<td><input type="number" name="format[volume][]" class="layui-input" autocomplete="off" value=""/></td>';
                html += '<td><button class="layui-btn layui-btn-xs layui-btn-danger format-del">删除</button></td>';
                html += '</tr>';
            })
            html += '</tbody>';
            $("#format_table").html(html)
            $("#format_table_temp_div").show()
            $("#format_table_div").show()
        })

        // 规格删除
        $("#format_table").on('click', '.format-del', function () {
            $(this).parent().parent().remove()
        })

        // 笛尔积算法
        function calcDescartes(array) {
            if (array.length < 2) return array[0] || [];
            return [].reduce.call(array, function (col, set) {
                var res = [];
                col.forEach(function (c) {
                    set.forEach(function (s) {
                        var t = [].concat(Array.isArray(c) ? c : [c]);
                        t.push(s);
                        res.push(t);
                    })
                });
                return res;
            });
        }
    });


</script>
</body>
</html>
